﻿using Handday.Erp.Core;
using HandDay.Framework.Common;
using Microsoft.EntityFrameworkCore;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace Handday.Erp.Transfer.Context
{
    /// <summary>
    /// TransferDbContext
    /// </summary>
    public class TransferDbContext : BaseDbContext<TransferDbContext>
    {
        /// <summary>
        /// ctor
        /// </summary>
        public TransferDbContext(DbContextOptions options, ISplitTableInfo splitTableInfo) : base(options, splitTableInfo)
        {
        }

        /// <summary>
        /// 实体模型配置
        /// </summary>
        /// <param name="modelBuilder">ModelBuilder</param>
        public override void OnModelCreate(ModelBuilder modelBuilder)
        {
            modelBuilder.ApplyConfigurationsFromAssembly(GetType().Assembly);
        }

        /// <summary>
        /// SaveChangesAsync
        /// </summary>
        public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default)
        {
            foreach (var item in ChangeTracker.Entries())
            {
                if (item.State == EntityState.Added)
                {
                    if (item.Entity is TransferEntity entity)
                    {
                        entity.CreateTime = DateTimeOffset.Now;
                        entity.UpdateTime = DateTimeOffset.Now;
                        entity.BusinessId = entity.BusinessId <= 0 ? UniqueIdBulder.Default.NextLong() : entity.BusinessId;
                        entity.Status = 1;
                    }
                }
                else if (item.State == EntityState.Modified)
                {
                    if (item.Entity is TransferEntity entity)
                    {
                        entity.UpdateTime = DateTimeOffset.Now;
                    }
                }
            }

            return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
        }
    }
}